#!/usr/bin/env bash
#Copyright (C) 2009-2014:
#    Gabes Jean, naparuba@gmail.com
#    Gerhard Lausser, Gerhard.Lausser@consol.de
#
#This file is part of Shinken.
#
#Shinken is free software: you can redistribute it and/or modify
#it under the terms of the GNU Affero General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#
#Shinken is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU Affero General Public License for more details.
#
#You should have received a copy of the GNU Affero General Public License
#along with Shinken.  If not, see <http://www.gnu.org/licenses/>.

TESTLIST=$1
COVERAGE=$2
PYLINT=$3
TESTLIST=$(readlink -f $TESTLIST)
test "$COVERAGE" == "COVERAGE" || COVERAGE="NOCOVERAGE"
test "$PYLINT" == "PYLINT" || PYLINT="NOPYLINT"
test "$PYTHONVERS" == "" && PYTHONVERS=27
test "$PYTHONVERS" == "27" && PYTHONVERS=2.7.1
test "$PYTHONVERS" == "26" && PYTHONVERS=2.6.6
test "$PYTHONVERS" == "24" && PYTHONVERS=2.4.6
PYTHONBIN=${PYTHONBIN:-/opt/python-${PYTHONVERS}/bin/python}
PYTHONTOOLS=${PYTHONTOOLS:-/opt/python-${PYTHONVERS}/bin}


DIR=$(cd $(dirname "$0"); pwd)
cd ${DIR}/..
echo `pwd`

# Cleanup leftover files from former runs
rm -f nosetests.xml
test $COVERAGE == "COVERAGE" && rm -f coverage.xml
test $COVERAGE == "COVERAGE" && rm -f .coverage

function launch_and_assert {
    SCRIPT=$1
    if test $COVERAGE == "NOCOVERAGE"; then
      ${PYTHONTOOLS}/nosetests -v -s --with-xunit ./$SCRIPT --xunit-file=TEST-$SCRIPT.xml
    else
      ${PYTHONTOOLS}/nosetests -v -s --with-xunit --with-coverage ./$SCRIPT --xunit-file=TEST-$SCRIPT.xml
    fi
    if [ $? != 0 ]
        then
        echo "Error: the test $SCRIPT failed"
        exit 2
    else
        echo "test $SCRIPT succeeded, next one"
    fi
}

echo "#All tests in the tests directory are listed below" >  ${DIR}/all_tests.txt
echo "#### AUTOGENERATED ####" >> ${DIR}/all_tests.txt

for file in test_*.py;do
    echo "$file" >>  ${DIR}/all_tests.txt
done

# We this we drop commented line and empty lines.
# We could have used "only" grep -v "#" because the $() return only one line and
# multiple space are skipped by the for loop
# Safer to drop at the very beginning
for line in $(grep -vE "#|^ *$" $TESTLIST);do
    launch_and_assert $line
done


# Create the coverage file
if test $COVERAGE == "COVERAGE"; then
  echo merging coverage files
  ${PYTHONTOOLS}/coverage xml --omit=/usr/lib
  ${PYTHONTOOLS}/coverage html --omit=/usr/lib
fi
if test $PYLINT == "PYLINT"; then
  cd ..
  echo checking the code with pylint
  ${PYTHONTOOLS}/pylint --rcfile test/jenkins/pylint.rc shinken > pylint.txt
fi

if test $COVERAGE == "COVERAGE" && test $PYLINT == "PYLINT"; then
  # this run's purpose was to collect metrics, so let jenkins think, it's ok
  exit 0
fi

